﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace JaxaraRnD.Helpers.DataAccess
{
    public class NHibernateHelper
    {
        public static ISessionFactory SessionFactory { get; private set; }

        public static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey(JaxaraRnDUtility.Constants.DEFAULT_CONNECTION)))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateHelper>())
                .ExposeConfiguration(c => new SchemaUpdate(c).Execute(false, true))
                .BuildConfiguration()
                .BuildSessionFactory();
        }

        public static ISession GetSession()
        {
            if (SessionFactory != null)
            {
                return SessionFactory.OpenSession();
            }

            SessionFactory = CreateSessionFactory();

            return SessionFactory.OpenSession();
        }
    }
}